package com.zs.grain.ui

import CommonDialog
import android.app.Dialog
import android.content.ComponentName
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.PagerAdapter
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.tabs.TabLayout
import com.zs.grain.ARouterPath
import com.zs.grain.R
import com.zs.grain.databinding.ActivityMaintenanceBinding
import com.jeremyliao.liveeventbus.LiveEventBus
import com.xnkj1688.semplibrary.mvvm.BaseMvvmActivity
import com.xnkj1688.semplibrary.mvvm.ViewManager
import com.xnkj1688.semplibrary.viewpager.ViewPagerAdapter
import com.zs.grain.tool.clockManage.LocalDataBase
import com.zslibrary.BusMaster.BusMaster
import java.util.*
import androidx.lifecycle.Observer

@Route(path = ARouterPath.MaintenanceActivity)
class MaintenanceActivity : BaseMvvmActivity<ActivityMaintenanceBinding, MaintenanceViewModel>() {
    override val layoutId = R.layout.activity_maintenance

    override fun initViewModel(binding: ActivityMaintenanceBinding) {
        binding.vm = this.mViewModel
        binding.view = this

        LiveEventBus.get("AutoRestart", Boolean::class.java)
            .observe(this, Observer {
                mViewModel.insertLog("Operation:自动重启")
            })

        ARouter.getInstance().inject(this);
        mViewModel.recentCard.value = this.cardNumber
    }

    @JvmField
    @Autowired
    var auth= ""

    @JvmField
    @Autowired
    var cardNumber= ""

    val pagerAdapter: PagerAdapter
        get() {
            val fragments = ArrayList<Fragment>()
            when (auth) {
                "1" -> {
                    mViewModel.cAuth.value = "维护"
                    fragments.add(ARouter.getInstance().build(ARouterPath.DailyFragment).withString("title","日常维护").navigation() as Fragment)
//                    fragments.add(ARouter.getInstance().build(ARouterPath.SettingFragment).withString("title","系统管理").navigation() as Fragment)
//                    fragments.add(ARouter.getInstance().build(ARouterPath.TestFragment).withString("title","设备测试").navigation() as Fragment)
//                    fragments.add(ARouter.getInstance().build(ARouterPath.ReceipeFragment).withString("title","配方管理").navigation() as Fragment)
                    //fragments.add(ARouter.getInstance().build(ARouterPath.AdvertisementFragment).withString("title","测试页面").navigation() as Fragment)
                }
                "2" -> {
                    mViewModel.cAuth.value = "运维"
                    fragments.add(ARouter.getInstance().build(ARouterPath.DailyFragment).withString("title","日常维护").navigation() as Fragment)
                    fragments.add(ARouter.getInstance().build(ARouterPath.SettingFragment).withString("title","系统管理").navigation() as Fragment)
                    fragments.add(ARouter.getInstance().build(ARouterPath.TestFragment).withString("title","设备测试").navigation() as Fragment)
                    fragments.add(ARouter.getInstance().build(ARouterPath.ReceipeFragment).withString("title","配方管理").navigation() as Fragment)
                    //fragments.add(ARouter.getInstance().build(ARouterPath.AdvertisementFragment).withString("title","测试页面").navigation() as Fragment)
                }
                "3" -> {
                    mViewModel.cAuth.value = "开发"
                    fragments.add(ARouter.getInstance().build(ARouterPath.DailyFragment).withString("title","日常维护").navigation() as Fragment)
                    fragments.add(ARouter.getInstance().build(ARouterPath.SettingFragment).withString("title","系统管理").navigation() as Fragment)
                    fragments.add(ARouter.getInstance().build(ARouterPath.TestFragment).withString("title","设备测试").navigation() as Fragment)
                    fragments.add(ARouter.getInstance().build(ARouterPath.ReceipeFragment).withString("title","配方管理").navigation() as Fragment)
                }
                "null"->{
                    mViewModel.cAuth.value = "未获取"
                    fragments.add(ARouter.getInstance().build(ARouterPath.DailyFragment).withString("title","日常维护").navigation() as Fragment)
//                    fragments.add(ARouter.getInstance().build(ARouterPath.SettingFragment).withString("title","系统管理").navigation() as Fragment)
//                    fragments.add(ARouter.getInstance().build(ARouterPath.TestFragment).withString("title","设备测试").navigation() as Fragment)
//                    fragments.add(ARouter.getInstance().build(ARouterPath.ReceipeFragment).withString("title","配方管理").navigation() as Fragment)
                    //fragments.add(ARouter.getInstance().build(ARouterPath.AdvertisementFragment).withString("title","测试页面").navigation() as Fragment)
                }
            }
            return ViewPagerAdapter(supportFragmentManager, fragments)
        }

    val tab: TabLayout
        get() = mBinding.tabLayout


    override fun onUiNotify(name: String, bundle: Bundle) {
        super.onUiNotify(name, bundle)
        when (name) {
            "Exit" -> ViewManager.instance.finishActivity()
            "Quit" -> {
                var homeIntent = Intent(Intent.ACTION_MAIN, null)
                homeIntent.addCategory(Intent.CATEGORY_HOME)
                val list = packageManager.queryIntentActivities(homeIntent, 0)
                val info = list[0]
                val pkg = info.activityInfo.packageName
                val cls = info.activityInfo.name
                val componet = ComponentName(pkg, cls)
                homeIntent = Intent()
                homeIntent.component = componet
                startActivity(homeIntent)
                ViewManager.instance.exitApp(this)
            }
            "Reboot" -> {
                Intent().also { intent ->
                    intent.setAction(Intent.ACTION_REBOOT)
                    intent.putExtra("nowait", 1)
                    intent.putExtra("interval", 1)
                    intent.putExtra("window", 0)
                    sendBroadcast(intent)
                }
            }
        }
    }

      fun onQuit() {
          CommonDialog.Builder(this)
                  .setPositiveButton("是", DialogInterface.OnClickListener { p0, p1 ->
                      p0?.dismiss()
                      this.mViewModel.mDataService.insertLog("State:应用退出")
                      var homeIntent = Intent(Intent.ACTION_MAIN, null)
                      homeIntent.addCategory(Intent.CATEGORY_HOME)
                      val list = this.packageManager.queryIntentActivities(homeIntent, 0)
                      val info = list[0]
                      val pkg = info.activityInfo.packageName
                      val cls = info.activityInfo.name
                      val componet = ComponentName(pkg, cls)
                      homeIntent = Intent()
                      homeIntent.component = componet
                      startActivity(homeIntent)
                      ViewManager.instance.exitApp(this)
                      System.exit(0)
                  })
                  .setNegativeButton("否", DialogInterface.OnClickListener { p0, p1 -> p0?.dismiss() })
                  .setWith(0.77f)
                  .create(true,R.layout.dialog_yes_no,R.id.yesButton,R.id.noButton)
                  .show()
      }
    var dialog: Dialog? = null;
    fun onExit() {
        var exitTemp = "返回售卖页面"
        if(!mViewModel.mDeviceService.errorsString.isEmpty()){
            exitTemp = "有异常未处理,确认退出?"

            dialog = CommonDialog.Builder(this)
                .setTitle(exitTemp)
                .setPositiveButton("确定", DialogInterface.OnClickListener { p0, p1 ->
                    p0?.dismiss()
                    mViewModel.mDeviceService.isMaintenance = false
                    this.mViewModel.mDataService.insertLog("Operation:返回售卖")
                    ViewManager.instance.finishActivity()
                })
                .setNegativeButton("取消", DialogInterface.OnClickListener { p0, p1 ->
                    p0?.dismiss()
                    //BusMaster.getInstance(context).cancelDurationTest(componentId.toShort(), Id.toShort())
                })
                .setWith(1.0f)
                .create(
                    false,
                    R.layout.dialog_toast_img,
                    R.id.yesButton,
                    R.id.noButton
                );
            dialog?.show()
        }else {

            dialog = CommonDialog.Builder(this)
                .setTitle(exitTemp)
                .setPositiveButton("确定", DialogInterface.OnClickListener { p0, p1 ->
                    p0?.dismiss()
                    mViewModel.mDeviceService.isMaintenance = false
                    this.mViewModel.mDataService.insertLog("Operation:返回售卖")
                    ViewManager.instance.finishActivity()
                })
                .setNegativeButton("取消", DialogInterface.OnClickListener { p0, p1 ->
                    p0?.dismiss()
                    //BusMaster.getInstance(context).cancelDurationTest(componentId.toShort(), Id.toShort())
                })
                .setWith(1.0f)
                .create(
                    false,
                    R.layout.dialog_toast1,
                    R.id.yesButton,
                    R.id.noButton
                );
            dialog?.show()
        }
//        CommonDialog.Builder(this)
//                .setPositiveButton("是", DialogInterface.OnClickListener { p0, p1 ->
//                    p0?.dismiss()
//                    mViewModel.mDeviceService.isMaintenance = false
//                    this.mViewModel.mDataService.insertLog("Operation:返回售卖")
//                    ViewManager.getInstance().finishActivity()
//                })
//                .setNegativeButton("否", DialogInterface.OnClickListener { p0, p1 -> p0?.dismiss() })
//                .setWith(0.77f)
//                .create(true,R.layout.dialog_yes_no,R.id.yesButton,R.id.noButton)
//                .show()
    }

    fun onReboot(){
        CommonDialog.Builder(this)
                .setPositiveButton("是", DialogInterface.OnClickListener { p0, p1 ->
                    p0?.dismiss()
                    this.mViewModel.mDataService.insertLog("Operation:重启整机")
                    //busMaster = BusMaster(applicationContext)
                    BusMaster.getInstance(this).resetBoard()
	                val componetName =  ComponentName("com.example.reboottest","com.example.reboottest.MainActivity");
                    val intent =  Intent();
                    intent.setComponent(componetName);
                    startActivity(intent);
                })
                .setNegativeButton("否", DialogInterface.OnClickListener { p0, p1 -> p0?.dismiss() })
                .setWith(0.77f)
                .create(true,R.layout.dialog_yes_no,R.id.yesButton,R.id.noButton)
                .show()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Log.e("TAG", "这是监听键盘操作，按下了Back键")
        } else if (keyCode == 0) {
            Log.e("TAG", "监听键盘操作，按下了服务按键")
            LiveEventBus.get("KeyEvent").post(true)
        }
        return super.onKeyDown(keyCode, event)
    }
}
